//
//  OAuhtViewController.swift
//  WeiBoOfSwift
//
//  Created by aven wu on 23/04/2018.
//  Copyright © 2018 GML. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuhtViewController: UIViewController {

    let APPKEY = "1438544723"
    let APPSECRET = "0fe6a3c6ae293d369d751c18f5b7df75"
    let REDIRECT_URL = "www.baidu.com"
    override func viewDidLoad() {
        super.viewDidLoad()
         navigationItem.leftBarButtonItem  = UIBarButtonItem.creatCustomBarButtonItem(imageName: "", highlightedName: "",title:"关闭", target: self, action: #selector(closeVC))
        
        view = webView
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URL)"
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(url: url! as URL)
        webView.delegate = self
        webView.scalesPageToFit = true
        webView.loadRequest(request as URLRequest)
        
    }
    @objc private func closeVC(){
        dismiss(animated: true, completion: nil)
    }
    
    private lazy var webView:UIWebView = {
       let web = UIWebView()
        return web
    }()

}

extension OAuhtViewController:UIWebViewDelegate {
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show(withStatus: "loading")
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
    }
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // http://www.baidu.com/?code=742683fc70f4db090c0995770bcadede
        // 格式 REDIRECT_URL+code token
        let absoluteString = request.url!.absoluteString
        print(absoluteString)
        if absoluteString.contains(REDIRECT_URL){
            if absoluteString.contains("code"){
                let codeRange = absoluteString.range(of: "code=")
                let codeToken = absoluteString[codeRange!.upperBound ..< absoluteString.endIndex]
                loadAccessToken(code: String(codeToken))
                return false
            }
        }
        return true
    }
    func loadAccessToken(code:String) -> Void {
        // access_token
        let path = "oauth2/access_token"
        let param = ["client_id":APPKEY,"client_secret":APPSECRET,"grant_type":"authorization_code","code":code,"redirect_uri":REDIRECT_URL] as [String : Any]
        NetWorkTools.shareNetWorkTools().post(path, parameters: param, progress: nil, success: { (_,json) -> Void in
            let dic = json as! [String:Any]
            let userModel = UserOauthModel()
            let params = ["access_token":dic["access_token"] as? String,"uid":dic["uid"] as? String]
            userModel.requestUserInfo(params: params, finished: { (userModel , error) in
                print(userModel?.access_token)
            })
            
        }) { (_, error) -> Void in
            print("失败--------\(error)")
        }
        
    }
    
    
}
